package com.huang.gulimail.product.Exception;

import com.huang.common.exception.BizCodeEnume;
import com.huang.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static com.huang.common.exception.BizCodeEnume.UKKNOW_EXCEPTION;

@Slf4j
@RestControllerAdvice(basePackages = "com.huang.gulimail.product.controller")
public class GulimailControllerAdvice {
    //可以先使用Exception.class用log打印异常类型在进行填写
    @ExceptionHandler(value=MethodArgumentNotValidException.class)
    public R handleVaild(MethodArgumentNotValidException e){
        log.error(e.getMessage(),e.getClass());
        Map<String,String>errorMap=new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_UKKNOW_EXCEPTION.getCode(),BizCodeEnume.VAILD_UKKNOW_EXCEPTION.getMsg()).put("data",errorMap);

    }
//    @ExceptionHandler(Throwable.class)
//    public R handleError(Throwable e){
//        return R.error(UKKNOW_EXCEPTION.getCode(),UKKNOW_EXCEPTION.getMsg());
//    }

}
